package com.lzb.permanentcalendar.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lzb.permanentcalendar.BaseAc;
import com.lzb.permanentcalendar.BaseApplication;
import com.lzb.permanentcalendar.R;
import com.lzb.permanentcalendar.adapter.CityAdapter;
import com.lzb.permanentcalendar.adapter.CitySearchAdapter;
import com.lzb.permanentcalendar.bean.CityBean;
import com.lzb.permanentcalendar.databinding.ActivitySelCityBinding;

import java.util.ArrayList;
import java.util.List;

public class SelCityActivity extends BaseAc<ActivitySelCityBinding> {

    private CityAdapter adapter;
    private List<String> letters = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.activity_sel_city;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSelCityBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mDataBinding.recyclerView.setLayoutManager(linearLayoutManager);
        List<CityBean> items = BaseApplication.items;
        // 设置布局管理器
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return adapter.getItemViewType(position) == CityAdapter.TYPE_HEADER ? 3 : 1;
            }
        });
        mDataBinding.recyclerView.setLayoutManager(layoutManager);

        // 设置适配器
        adapter = new CityAdapter();
        mDataBinding.recyclerView.setAdapter(adapter);
        adapter.setData(items);
        List<CityBean> list = new ArrayList<>();
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(this);
        mDataBinding.recy1.setLayoutManager(linearLayoutManager1);
        CitySearchAdapter citySearchAdapter = new CitySearchAdapter(R.layout.item_search, list);
        mDataBinding.recy1.setAdapter(citySearchAdapter);
        // 初始化侧边栏
        initSideBar(mDataBinding.sideBar);
        // 监听输入框内容变化
        mDataBinding.etText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 触发过滤
                if (s.length() == 0) {
                    mDataBinding.rely.setVisibility(View.VISIBLE);
                    mDataBinding.recy1.setVisibility(View.GONE);
                } else {
                    mDataBinding.rely.setVisibility(View.GONE);
                    mDataBinding.recy1.setVisibility(View.VISIBLE);
                    List<CityBean> cityBeans = new ArrayList<>();
                    for (int i = 0; i < items.size(); i++) {
                        if (items.get(i).getCityName().contains(s.toString())) {
                            CityBean cityBean = items.get(i);
                            cityBeans.add(cityBean);
                        }
                    }
                    citySearchAdapter.setNewData(cityBeans);
                }
            }
        });
        citySearchAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                //选择城市返回
                if (position < citySearchAdapter.getData().size()) {
                    CityBean cityBean = citySearchAdapter.getData().get(position);
                    Intent intent = getIntent();
                    intent.putExtra("bean", cityBean);
                    setResult(200, intent);
                    finish();
                }
            }
        });
        adapter.setOnItemClickListener(new CityAdapter.OnItemClickListener() {
            @Override
            public void OnClick(CityBean bean) {
                Intent intent = getIntent();
                intent.putExtra("bean", bean);
                setResult(200, intent);
                finish();
            }
        });
        mDataBinding.etText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mDataBinding.rely.setVisibility(View.GONE);
                    mDataBinding.recy1.setVisibility(View.VISIBLE);
                } else {
                    mDataBinding.rely.setVisibility(View.VISIBLE);
                    mDataBinding.recy1.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    private void initSideBar(LinearLayout sideBar) {
        // 获取所有存在的首字母（保持不变）
        letters.clear();
        for (Object item : adapter.dataList) {
            if (item instanceof String && !letters.contains(item)) {
                letters.add((String) item);
            }
        }

        // 动态添加TextView（保持不变）
        for (String letter : letters) {
            TextView textView = new TextView(this);
            textView.setText(letter);
            textView.setTextSize(12);
            textView.setGravity(Gravity.CENTER);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 0, 1);
            textView.setLayoutParams(params);
            sideBar.addView(textView);
        }

        // 修正后的触摸监听设置
        sideBar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        handleTouch(v, event.getY());
                        return true;
                    case MotionEvent.ACTION_UP:
                        mDataBinding.tvLetterHint.setVisibility(View.GONE);
                        return true;
                }
                return false;
            }

            private void handleTouch(View sideBarView, float y) {
                int itemHeight = sideBarView.getHeight() / letters.size();
                int index = (int) (y / itemHeight);
                index = Math.max(0, Math.min(index, letters.size() - 1));

                String selectedLetter = letters.get(index);
                mDataBinding.tvLetterHint.setText(selectedLetter);
                mDataBinding.tvLetterHint.setVisibility(View.VISIBLE);

                int pos = adapter.getLetterPosition(selectedLetter);
                if (pos != -1) {
                    ((LinearLayoutManager) mDataBinding.recyclerView.getLayoutManager())
                            .scrollToPositionWithOffset(pos, 0);
                }
            }
        });
    }

}